import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { User } from "./entities/user.entity";
import { DeleteResult, Like, Repository } from "typeorm";
import { CreateUserDto } from "./dto/create-user.dto";
import { UpdateUserDto } from "./dto/update-user.dto";
import * as md5 from "md5";

/**
 * @Injectable()：标记该类为一个可注入的服务
 * @InjectRepository(User)：注入用户实体的 Repository，用于操作数据库
 * userRepository：TypeORM 提供的 Repository 对象，用于执行数据库操作
 */

@Injectable() 
export class UserService {
    constructor(
        @InjectRepository(User) // 注入用户的实体
        private readonly userRepository:Repository<User> // 针对于上一行User数据库实体的实例
    ){}
    // 查询某个用户的信息
    findOne(id:number):Promise<User | null> {
        return this.userRepository.findOneBy({ id })
    }
    // 查询所有用户
    findAll(query):Promise<User[]> {
        const where:any = {}
        if(query.username) {
            where.username = Like(`%${query.username}%`)
        }
        if(query.active) {
            where.active = query.active
        }
        return this.userRepository.find({
            where: where
        })
    }
    // 创建用户
    create(createUserDto:CreateUserDto):Promise<User> {
        return this.userRepository.save(createUserDto)
    }
    // 更新用户
    update(user:Partial<UpdateUserDto>) {
        if(user.id) {
            return this.userRepository.update(user.id, user)
        }
    }
    // 删除用户
    delete(id:string):Promise<DeleteResult> {
        return this.userRepository.delete(id)
    }
    // 根据用户名查找用户是否存在
    findByUsername(username:string):Promise<User | null> {
        return this.userRepository.findOneBy({ username })
    }
    // 重置用户密码
    resetPwd(id: string) {
        return this.userRepository.update(id, {password: md5('123456')})
    }
}